<?php
  require_once('conn.php');
  
  // 接收由登录页面传来的数据
  $username = $_POST['username'];
  $password1 = $_POST['password1'];
  $password2 = $_POST['password2'];
  $sql = "select * from user where username = '$username'";
  $result = mysqli_query($conn, $sql);
  if(mysqli_num_rows($result) > 0) {
    alert('该用户名已存在', 'register.php');
    exit();
  }
  if(strlen($username) < 5) {
    alert('用户名不能小于5位', 'register.php');
    exit();
  }
  if($password1 != $password2) {
    alert('两次输入密码不相同，请重新输入', 'login.php');
    exit();
  }

  $sql = "insert into user (username, password) values ('$username', '$password1')";
  $result = mysqli_query($conn, $sql);
  if($result) {
    $_SESSION['username'] = $username;
    alert('注册成功', 'login.php');
  } else {
    alert('注册失败', 'register.php');
  }

  mysqli_close($conn);
?>